import MenuList from '../mock/menuList.json'
export default {
  data() {
    return {
      menuList: [],
      routes: [],
      openKeys: [], // 选中的一级菜单
      selectedKeys: []  // 选中的二级菜单
    }
  },
  watch: {
    '$route'() {
      this.getRoutes()
    }
  },
  methods: {
    getRoutes() {
      let routePath = this.$route.path
      MenuList.some(item => {
        if (item.children) {
          // 二级菜单
          item.children.some(items => {
            if (items.menuUrl === routePath) {
              this.routes = [item, items]
              return true
            }
          })
        } else {
          // 一级菜单
          if (item.menuUrl === routePath) {
            this.routes = [item]
            return true
          }
        }
      })
      this.setKeys()
    },
    setKeys() {
      switch (this.routes.length) {
        case 1:
          this.selectedKeys = [this.routes[0].menuId]
          break
        case 2:
          this.openKeys = [this.routes[0].menuId]
          this.selectedKeys = [this.routes[1].menuId]
      }
    },
    onOpenChange(openKeys) {
      const latestOpenKey = openKeys.find(key => this.openKeys.indexOf(key) === -1)
      if (this.menuList.findIndex(v => v.menuId === latestOpenKey) === -1) {
        this.openKeys = openKeys
      } else {
        this.openKeys = latestOpenKey ? [latestOpenKey] : []
      }
    },
  },
  created() {
    this.menuList = MenuList
    this.getRoutes()
  }
}